'''
把日志文件里的ip，时间字段获取出来，时间格式转化为“2021-11-24 12:00:00", 通过ip解析出它属于哪个省份和运营商
json模块  把字典一样的字符串转化成字典
结果写入另一个文件
'''

import requests
import os
import json
if os.path.exists('a.txt'):
    os.remove('a.txt')
with open('scwebsite2_ssl.log','r') as fp:
    for i in fp:
        s=i.split()
        j=s[3].replace('Jun','06').replace('[','').split('/')
        j1=j[2].split(':')

        url="http://ip.aliyun.com/outGetIpInfo?accessKey=alibaba-inc&ip="+s[0]
        re=json.loads(requests.get(url).text)
        print(re)
        with open('a.txt','a',encoding='utf-8') as f:
            f.write(f"ip地址为：{s[0]}  时间为：{j1[0]}-{j[1]}-{j[0]} {j1[1]}:{j1[2]}:{j1[3]} 所属国家：{re['data']['country']} 省份:{re['data']['region']} 城市：{re['data']['city']} 所属运营商：{re['data']['isp']}\n")